<template>
  <div class="app-container">
    <!-- 搜索工作栏   出库单-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="单据编号" prop="taskNo">
        <el-input v-model="queryParams.taskNo" placeholder="请输入单据编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="来源单号" prop="sourceNo">
        <el-input v-model="queryParams.sourceNo" placeholder="请输入来源单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.OUTBOUND_TYPE)" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="出库仓库" prop="outWarehouseId">
        <treeselect v-model="queryParams.outWarehouseId" :options="warehouseTree" :normalizer="normalizerW"
                    placeholder="选择出库仓库" style="width: 180px" @select="onWarehouseChange"/>
      </el-form-item>
      <el-form-item label="出库库位" prop="outStoreId">
        <el-select v-model="queryParams.outStoreId" placeholder="请选择出库库位" clearable size="small"
                   style="width: 180px">
          <el-option v-for="location in locationList" :key="location.id" :label="location.storageLocationName"
                     :value="location.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入库仓库" prop="inWarehouseId">
        <treeselect v-model="queryParams.inWarehouseId" :options="warehouseTree" :normalizer="normalizerW"
                    placeholder="选择入库仓库" style="width: 180px" @select="onWarehouseInChange"/>
      </el-form-item>
      <el-form-item label="入库库位" prop="inStoreId">
        <el-select v-model="queryParams.inStoreId" placeholder="请选择入库库位" clearable size="small"
                   style="width: 180px">
          <el-option v-for="location in locationInList" :key="location.id" :label="location.storageLocationName"
                     :value="location.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编码" prop="materialNo">
        <el-input v-model="queryParams.materialNo" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!--      <el-form-item label="单据状态" prop="status">-->
      <!--        <el-select v-model="queryParams.status" placeholder="请选择单据状态" filterable clearable size="small">-->
      <!--          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.OUT_STATE)" :key="dict.value" :label="dict.label"-->
      <!--                     :value="parseInt(dict.value)"/>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"-->
      <!--                   v-hasPermi="['warehouse:order-task-out:create']">新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"-->
      <!--                   :loading="exportLoading"-->
      <!--                   v-hasPermi="['warehouse:order-task-out:export']">导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="isEmpty(checkedIds)"-->
      <!--          @click="handleDeleteBatch"-->
      <!--          v-hasPermi="['warehouse:order-task-out:delete']"-->
      <!--        >-->
      <!--          批量删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="单据编号" align="center" prop="taskNo"/>
      <el-table-column label="质检来源类型" align="center" prop="sourceTypeName"/>
      <el-table-column label="来源单号" align="center" prop="sourceNo"/>
      <el-table-column label="业务类型" align="center" prop="businessTypeName"/>
      <el-table-column label="出库仓库" align="center" prop="outWarehouseName"/>
      <el-table-column label="出库库位" align="center" prop="outStoreName"/>
      <el-table-column label="入库仓库" align="center" prop="inWarehouseName"/>
      <el-table-column label="入库库位" align="center" prop="inStoreName"/>
      <el-table-column label="物料编码" align="center" prop="materialNo"/>
      <el-table-column label="物料名称" align="center" prop="materialName"/>
      <el-table-column label="批次号" align="center" prop="batchNo"/>
      <el-table-column label="数量" align="center" prop="quantity"/>
      <el-table-column label="单据状态" align="center" prop="status">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.OUT_STATE, scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="creator"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template v-slot="scope">-->
      <!--          <el-button v-if="scope.row.status !== 4 && scope.row.status !== 5" size="mini" type="text"-->
      <!--                     icon="el-icon-document-checked" @click="finishForm(scope.row)">-->
      <!--            完结-->
      <!--          </el-button>-->
      <!--          <el-button v-if="scope.row.status !== 4 && scope.row.status !== 5" size="mini" type="text"-->
      <!--                     icon="el-icon-folder-delete" @click="clearForm(scope.row)">-->
      <!--            取消-->
      <!--          </el-button>-->
      <!--          &lt;!&ndash;          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"&ndash;&gt;-->
      <!--          &lt;!&ndash;                     v-hasPermi="['warehouse:order-task-out:update']">修改&ndash;&gt;-->
      <!--          &lt;!&ndash;          </el-button>&ndash;&gt;-->
      <!--          &lt;!&ndash;          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"&ndash;&gt;-->
      <!--          &lt;!&ndash;                     v-hasPermi="['warehouse:order-task-out:delete']">删除&ndash;&gt;-->
      <!--          &lt;!&ndash;          </el-button>&ndash;&gt;-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
  </div>
</template>

<script>
import * as OrderTaskApi from '@/api/warehouse/orderTask';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'
import * as WarehouseApi from "@/api/storage/warehouse";
import * as LocationApi from "@/api/storage/location";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "OrderOutRecord",
  components: {
    Treeselect
  },
  data() {
    return {
      // 仓库树数据
      warehouseTree: [],
      // 仓库树加载状态
      treeLoading: false,
      // 库位列表
      locationList: [],
      locationInList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库出/入库任务列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        taskNo: null,
        // orderType: 2,
        orderTypeList: [4, 5],
        storageOrderId: null,
        storageOrderMaterialId: null,
        sourceType: null,
        sourceTypeName: null,
        sourceNo: null,
        businessType: null,
        businessTypeName: null,
        outWarehouseId: null,
        outWarehouseName: null,
        outStoreId: null,
        outStoreName: null,
        inWarehouseId: null,
        inWarehouseName: null,
        inStoreId: null,
        inStoreName: null,
        materialId: null,
        materialNo: null,
        materialName: null,
        batchNo: null,
        quantity: null,
        status: 4,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getWarehouseTree();

  },
  methods: {
    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        this.treeLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        this.warehouseTree = res.data
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
        this.$modal.msgError('获取仓库树数据失败');
      } finally {
        this.treeLoading = false;
      }
    },


    /** 树节点标准化处理 */
    normalizerW(node) {
      const result = {
        id: node.id,
        label: node.warehouseName,
        children: undefined
      };
      // 只有当children存在且不为undefined且长度大于0时才添加该字段
      if (node.children && node.children.length > 0) {
        result.children = node.children;
      }
      return result;
    },

    /** 仓库选择变化时触发 */
    async onWarehouseChange(warehouseId) {
      this.queryParams.outStoreId = null;
      if (warehouseId) {
        await this.getLocationList(warehouseId.id);
      } else {
        this.locationList = [];
      }
    },
    /** 仓库选择变化时触发 */
    async onWarehouseInChange(warehouseId) {
      this.queryParams.inStoreId = null;
      if (warehouseId) {
        await this.getLocationInList(warehouseId.id);
      } else {
        this.locationList = [];
      }
    },

    /** 根据仓库ID获取库位列表 */
    async getLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationList = [];
      }
    },

    /** 根据仓库ID获取库位列表 */
    async getLocationInList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationInList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationInList = [];
      }
    },

    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await OrderTaskApi.getOrderTaskPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除仓库出/入库任务编号为"' + id + '"的数据项?')
      try {
        await OrderTaskApi.deleteOrderTask(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除仓库出/入库任务 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await OrderTaskApi.deleteOrderTaskList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有仓库出/入库任务数据项?');
      try {
        this.exportLoading = true;
        const data = await OrderTaskApi.exportOrderTaskExcel(this.queryParams);
        this.$download.excel(data, '仓库出/入库任务.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 完结单据 */
    async finishForm(row) {
      try {
        // 二次确认对话框
        await this.$confirm('确定要完结该单据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 调用完结接口，传递整行数据
        await OrderTaskApi.finish(row);

        // 刷新列表
        this.getList();

        // 提示成功
        this.$modal.msgSuccess('单据完结成功');
      } catch (error) {
        // 如果是用户取消，不显示错误信息
        if (error !== 'cancel') {
          this.$modal.msgError('单据完结失败');
        }
      }
    },

    /** 取消单据 */
    async clearForm(row) {
      try {
        // 弹出输入框获取取消原因
        const remark = await this.$prompt('请输入取消原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'textarea',
          inputPlaceholder: '请输入取消原因',
          inputValidator: (value) => {
            if (!value || value.trim() === '') {
              return '取消原因不能为空';
            }
            return true;
          }
        });

        // 设置取消原因
        row.remark = remark.value;

        // 调用取消接口，传递整行数据
        await OrderTaskApi.clear(row);

        // 刷新列表
        this.getList();

        // 提示成功
        this.$modal.msgSuccess('单据取消成功');
      } catch (error) {
        // 如果是用户取消，不显示错误信息
        if (error !== 'cancel') {
          this.$modal.msgError('单据取消失败');
        }
      }
    }
  }
};
</script>
